package org.atlantis.grosbeak.cable.template;

import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用于渲染一段文本的模板。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
public class TextTemplate implements Template {

	private String text;
	private String encoding;
	private String contentType = "text/html";

	public TextTemplate() {
		this("", null);
	}

	public TextTemplate(String text) {
		this(text, null);
	}

	public TextTemplate(String text, String encoding) {
		this.text = text;
		this.encoding = (encoding == null) ? "UTF-8" : encoding;
	}

	void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public void render(ServletContext sc, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		StringBuilder sb = new StringBuilder(100);
		sb.append(contentType).append(";charset=").append(encoding);
		response.setContentType(sb.toString());
		PrintWriter out = response.getWriter();
		out.write(text);
		out.flush();
		out.close();
	}
}
